<?php

namespace app\manage\services;

use app\common\loader\ModelSystem;
use app\common\loader\Services;
use app\manage\libs\ManageToken;
use app\manage\loader\ManageModel;
use think\Exception;
use think\facade\Cache;
use yiqiniu\extend\library\GlobalParam;

class ManagerService extends BaseService
{

    // 登录缓存有效期
    protected const TOKEN_TIMEOUT = DAY_SECOND * 3;
    // 登录权限的前缀
    protected const TOKEN_PREFIX = 'MANAGE_LOGIN_TOKEN';

    /**
     * 管理员登录
     * @param string $user
     * @param string $pass
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function login(string $user, string $pass)
    {

        //
        $adminInfo = ManageModel::SystemManger()->login($user, $pass);

        //生成加密TOKEN
        $authorization = $this->saveToken($adminInfo["id"], $adminInfo['passwd']);
        return [
            'authorization' => $authorization,
            "info" => [
                "true_name" => $adminInfo["nickname"],
                "mobile" => $adminInfo["mobile"],
                'is_super' => $adminInfo['is_super'],
            ]
        ];

    }

    /**
     * 保存到token到缓存中
     * @param int    $id 用户编号
     * @param string $password 密码
     * @return mixed
     * @throws \yiqiniu\extend\exception\ApiException
     */
    private function saveToken(int $id, string $password)
    {
        $app = GlobalParam::getInstance()->get('app');
        //生成加密TOKEN
        $adminUser = ['id' => $id, 'password' => md5($password), 'app' => $app];

        $token = ManageToken::getInstance()->getToken($adminUser);

        $authorization = $token['access_token'] ?? $token;
        //保存TOKEN入缓存
        Cache::set(self::TOKEN_PREFIX . $app . '_' . $id, $authorization, self::TOKEN_TIMEOUT);
        return $authorization;
    }


    /**
     * 验证登录
     * @param string $authorization 验证内容
     * @param string $app 终端类型
     * @param string $msg
     * @return array|false
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \yiqiniu\extend\exception\ApiException
     */
    public function verityLogin($authorization, $app, string &$msg)
    {
        $userInfo = ManageToken::getInstance()->verifyToken($authorization, $app);
        // 验证token是否成功 和 判断用户唯一性
        $cache = Cache::get(self::TOKEN_PREFIX . $app . '_' . $userInfo['id']);

        if (empty($cache) || $cache !== $authorization) {
            api_exception(API_TIMEOUT, '登录已过期或该账户在其他设备登录');
        }

        // 验证用户名 和密码 是否正确,判断用户是否禁用
        $adminInfo = ManageModel::SystemManger()->validUserInfo($userInfo, $msg);
        if (empty($adminInfo)) {
            return false;
        }

        Cache::set(self::TOKEN_PREFIX . $app . '_' . $adminInfo["id"], $authorization, self::TOKEN_TIMEOUT);

        return [
            "id" => $adminInfo["id"],
            "username" => $adminInfo["username"],
            "nick_name" => $adminInfo["nickname"],
            'super' => $adminInfo['is_super'] ?? 0,
            'mobile' => $adminInfo['mobile'],
            'group_id' => $adminInfo['role_id'],
        ];

    }

    /**
     * 管理员列表
     * @param array $option
     * @return array
     * @throws \think\db\exception\DbException
     */
    public function page(array $option)
    {
        $list = ManageModel::SystemManger()->pageList($option['where'] ?? [], $option['page_size'] ?? 30);
        Services::Helper()->showListTitle($list['data'], [], ['status' => 'system.status']);
        return $list;
    }

    /**
     * 管理员列表
     * @param array $option
     * @return array
     * @throws \think\db\exception\DbException
     */
    public function list(array $option)
    {
        $list = ManageModel::SystemManger()->adminList($option['where'] ?? []);
        return $list;
    }


    /**
     * 管理员详情
     * @param array $option
     * @return array
     * @throws \think\db\exception\DbException
     */
    public function info(array $option)
    {
        $list = ManageModel::SystemManger()->info($option);
       if (empty($list)){
            throw  new Exception('未找到该用户', API_ERROR);
        }
        return  $list;
    }

    /**
     * 添加虚码套餐
     * @param array  $params
     * @param string $scene
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DbException
     */
    public function Save(array $params, string $scene)
    {

        $packageModel = ManageModel::SystemManger();
        if ($scene === 'add') {
            $data = [
                'mobile' => $params['mobile'],        // 手机号码
                'is_super' => $params['is_super'] ?? 0,
                'username' => $params['username'] ?? ('by' . $params['mobile']),
                'passwd' => password($params['passwd']),
                'create_at' => date('Y-m-d H:i:s'),
                'dept_id' => $params['dept_id'],
                'role_id' => $params['role_id'],
            ];
            return $packageModel->insertGetId($data);
        }
        $data = [
            'username' => $params['username'],        // 手机号码
            'is_super' => $params['is_super'] ?? 0,
        ];
        if(!empty($params['passwd'])){
            $data['passwd'] = password($params['passwd']);
        }
        if(!empty($params['role_id'])){
            $data['role_id'] =$params['role_id'];
        }
        return $packageModel->removeOption()->where(['id' => $params['id']])
            ->update(null, $data);
    }


    /**
     * 设置管理员状态
     * @param int $id
     * @param int $status
     * @return mixed
     * @throws \think\db\exception\DbException
     */
    public function editStatus(int $id, int $status)
    {
        return ManageModel::SystemManger()->update([['id', '=', $id]], ['status' => $status]);
    }

    /**
     * 重置密码
     * @param int    $id
     * @param string $password
     * @return mixed
     * @throws \think\db\exception\DbException
     */
    public function resetPassword(int $id, string $password)
    {
        return ManageModel::SystemManger()->update([['id', '=', $id]], ['passwd' => password($password)]);
    }


    /**
     * 权限菜单
     * @param int    $group_id
     */
    public function getAction($group_id)
    {
       $data =   ModelSystem::SystemApi()->getActionsData($group_id);
       if (empty($data)){
           throw  new Exception('您暂无权限访问', API_ERROR);
       }
       return $data;
    }

}
